package com.paxcodi.rmi.chat;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;



@SuppressWarnings("serial")
public class ChatServer extends UnicastRemoteObject implements Chat {

    private List<ChatUser> chatUsers;

    ChatServer() throws RemoteException {
	/* creates a UniCastRemoteObject on some port 
	 * and starts it listening for connections
	 */
	super();
	chatUsers = new ArrayList<ChatUser>();
    }

    public void register(String userName) {
	//TODO does not handle duplicate usernames in any special way
	System.out.println("registering user: " + userName);
	chatUsers.add(new ChatUser(userName));
	outputRegisteredUsers();//debug or server status message
    }

    public void sendMsgFromUser(String nextLine, String userName) {
	//put message in queues of other users
	//i.e. iterate over users, when currentUser not sender, add message
	//to his/her queue of unread messages
	for (ChatUser currentUser : chatUsers) {
	    if(!(currentUser.getName().equals(userName))){
		currentUser.addToUnreadMessages(userName, nextLine);
	    }
	}
    }
    
    public String getMsgForUser(String userName) {
	//iterate over chatUsers and retrieve the right ChatUser obj
	ChatUser user = null;
	for (ChatUser currentUser : chatUsers) {
	    if(currentUser.getName().equals(userName)) {
		user = currentUser;
		break;
	    }
	}
	if(user == null)
	    throw new IllegalArgumentException("No User with name: " + userName);
	return user.pollFromUnreadMessages();
    }

    public void unregister(String userName) {
	//find index of userName
	//TODO replace loop with simple call to contains() on List, once handling
	//of duplicate names has been integrated
	System.out.println("unregistering user: " + userName);
	for( ChatUser currentUser : chatUsers ){
	    if(currentUser.getName().equals(userName)){
		chatUsers.remove(
			chatUsers.indexOf(currentUser));
	    }
	}
    }
    
    //debug - status messages
    private void outputRegisteredUsers(){
	System.out.println("\nregistered users at server:");
	for( ChatUser currentUser : chatUsers)
	    System.out.println(currentUser.getName() + " ");
	System.out.println("\n");
    }
    
    public static void main(String[] args) {
	try {
	    Chat chat = new ChatServer();
	    Naming.rebind("chat", chat);
	} catch (RemoteException e) {
	    System.err.println("Exception in ChatServer.main " + e);
	} catch (MalformedURLException e) {
	    System.err.println("Malformed URL Exception " + e);
	}
    }

}
